#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/stat.h>

// 检查本地是否存在指定的文件夹
int checkLocalFolder(const char *folderPath) {
    struct stat st;
    if (stat(folderPath, &st) == 0) {
        if (S_ISDIR(st.st_mode)) {
            return 1; // 文件夹存在
        }
    }
    return 0; // 文件夹不存在
}


int main(int argc, char *argv[]) {
    // 若参数不足，则打印使用方法并退出
    if (argc < 2) {
        fprintf(stderr, "Usage: sudo %s [mount|unmount] <local_mount_point> [username:password@webdav_address:port]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    // 检查本地文件夹是否存在
    if (!checkLocalFolder(argv[2])) {
        fprintf(stderr, "本地挂载点不存在！请确认挂载点存在或使用绝对路径\n");
        exit(EXIT_FAILURE);
    }
    // 添加环境变量
    system("export PATH=$PATH:/usr/local/sbin");

    char command[256];  //  命令缓冲区
    // snprintf(command, sizeof(command), "export PATH=$PATH:/usr/local/sbin"); 

    if (strcmp(argv[1], "umount") == 0) {      // 【卸载】   
        snprintf(command, sizeof(command), "sudo umount.davfs %s", argv[2]); 
        if(system(command) == -1){
            perror("执行失败，请检查是否已经挂载");
            exit(EXIT_FAILURE);
        }
        memset(command, 0, sizeof(command));  //  清空command缓冲区
    }else if (strcmp(argv[1], "mount") == 0) {    // 【挂载】
        //  检查参数数目
        if(argc != 4){
            fprintf(stderr, "Usage: %s [mount|unmount] <local_mount_point> [username:password@webdav_address:port]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
        //  解析参数
        char info[256];
        strcpy(info, argv[3]);  //  strtok函数需要修改原字符串，所以需要复制一份到char[]中，以支持修改
        char *username = strtok(info, ":");  //  获取用户名 
        char *password = strtok(NULL, "@");     //  获取密码
        //  获取webdav地址
        char *webdav_address = strtok(NULL, ":"); 
        char *token = strtok(NULL, ":");
        asprintf(&webdav_address, "%s%s%s", webdav_address, ":", token);
        char *port = strtok(NULL, "");         //  获取端口号
        
        //  更新secrets配置
        if(port == NULL){
            snprintf(command, sizeof(command), "echo \"%s %s %s\" >> /usr/local/etc/davfs2/secrets", webdav_address, username, password);
        }else{
            snprintf(command, sizeof(command), "echo \"%s:%s %s %s\" >> /usr/local/etc/davfs2/secrets", webdav_address, port, username, password);
        }
        if(system(command) == -1){
            perror("更新secrets配置失败");
            exit(EXIT_FAILURE);
        }
        memset(command, 0, sizeof(command));  //  清空command缓冲区

        //  执行挂载命令
        snprintf(command, sizeof(command), "sudo mount.davfs %s %s", webdav_address, argv[2]);
        if(system(command) == -1){
            perror("执行挂载命令失败");
            exit(EXIT_FAILURE);
        }{
            printf("挂载成功！\n");
        }
        memset(command, 0, sizeof(command));  //  清空command缓冲区
    } else {
        fprintf(stderr, "非法命令，请使用 'mount' 或 'unmount'.\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}